package com.example.lanouhn.firstapp.activity.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.adapter.SearchGoodsListAdapter;
import com.example.lanouhn.firstapp.activity.constants.Constants;
import com.example.lanouhn.firstapp.activity.model.SearchGoodsList;
import com.example.lanouhn.firstapp.activity.utils.HttpUtils;
import com.example.lanouhn.firstapp.activity.utils.SearchGoodsListJson;
import com.example.lanouhn.firstapp.activity.view.xlistview.XListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 首页搜索跳转商品搜索界面
 */
public class SearchGoodsListActivity extends AppCompatActivity {
    //返回
    private ImageView iv_back;

    //定义变量
    private XListView listView;
    private RadioGroup radioGroup;
    //一个中间量集合
    private List<SearchGoodsList> tempList;
    //排序类型
    private int key = 4;//4代表新品，3代表价格 2代表销量 1代表人气
    //当前页
    private int currentPage = 1;
    private int pageSize = 10;
    //升降序标识
    private boolean orderFlag = true;
    private int order = 1;//升序1，降序2

    private boolean isFirstRequest = true;
    private List<SearchGoodsList> list;
    private SearchGoodsListAdapter adapter;
    //加载进度
    private ProgressBar progressBar;
    //搜索按钮
    private TextView iv_goodsList;
    //搜索框
    private EditText et_search;
    //搜索无商品
    private TextView tv_noProduct;



    private Handler handler = new Handler() {


        @Override
        public void handleMessage(Message msg) {

            //取消进度
            progressBar.setVisibility(View.GONE);
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(SearchGoodsListActivity.this,
                            "网络链接失败，请稍后再试", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    tv_noProduct.setVisibility(View.GONE);
                    adapter = new SearchGoodsListAdapter(SearchGoodsListActivity.this, list);
                    listView.setAdapter(adapter);

                    listView.stopRefresh();
                    listView.setPullLoadEnable(true);
                    adapter.notifyDataSetChanged();

                    break;
                case 2://加载更多数据

                    //添加到原来的集合
                    String goodsId = tempList.get(0).getGoods_id();
                    //判断原来集合中是否存在当前id
                    List<String> ids = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        ids.add(list.get(i).getGoods_id());
                    }

                    if (ids.contains(goodsId)) {
                        //已经没有新数据了
                        Toast.makeText(SearchGoodsListActivity.this, "已经是最后一页啦！", Toast.LENGTH_SHORT).show();
                        //取消上拉加载更多
                        listView.setPullLoadEnable(false);
                    } else {
                        list.addAll(tempList);
                    }

                    //list.addAll(tempList);
                    //刷新页面
                    adapter.notifyDataSetChanged();
                    //清空中间集合量
                    tempList.removeAll(tempList);
                    //停止加载listView
                    listView.stopLoadMore();

                    break;
                case 3:
                    tv_noProduct.setVisibility(View.VISIBLE);
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchgoods_list);

        listView = (XListView) findViewById(R.id.listView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        //开启加载更多功能 设置上拉加载的开关
        listView.setPullLoadEnable(true);

        iv_goodsList = (TextView) findViewById(R.id.goodsList);
        et_search = (EditText) findViewById(R.id.et_search);

        tv_noProduct = (TextView) findViewById(R.id.tv_noProduct);

        //radioButton监听事件
        initEvent();
        //点击搜索按钮
        getStoreDataFromWeb();

    }

    private void getStoreDataFromWeb() {

        //搜索按钮监听事件
        iv_goodsList.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                final String keyword = et_search.getText().toString().trim();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //定义路径
                        String url = Constants.FLAGSHIP_STORE_URL +
                                "&key=" + key + "&order=" + order + "&curpage=" + currentPage + "&inkeyword=" + keyword;

                        String result = HttpUtils.doGet(url);
                        //判断数据是否解析成功
                        if (!result.equals("") && !result.equals("null")) {
                            //数据进行封装
                            list = SearchGoodsListJson.getSearchGoodsList(result);

                            //判断解析出的集合的长度，有数据就显示，无数据就不显示
                            if (list.size() > 0) {
                                //获取数据成功
                                handler.sendEmptyMessage(1);
                            } else {
                                handler.sendEmptyMessage(3);
                            }

                        } else {
                            //失败
                            handler.sendEmptyMessage(3);
                        }

                    }
                }).start();

                //第一次显示，第二次下拉刷新不显示
                isFirstRequest = false;
            }
        });

    }

    //radioButton点击选中事件
    private void initEvent() {
        //设置默认的RadioButton
        radioGroup.check(R.id.rb_newProduct);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_newProduct://新品
                        key = 4;
                        break;
                    case R.id.rb_price://价格
                        key = 3;
                        if (orderFlag)
                            order = 1;
                        else
                            order = 2;

                        orderFlag = !orderFlag;
                        break;
                    case R.id.rb_sales://销量
                        key = 2;
                        break;
                    case R.id.rb_popularity://人气
                        key = 1;
                        break;

                }
                //重新获取数据并填充listView
                getStoreDataFromWeb();

            }
        });
        //listView的刷新加载监听事件

        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                //下拉刷新
                currentPage ++;
                getStoreDataFromWeb();

            }

            @Override
            public void onLoadMore() {
                //上拉更多
                currentPage++;
                getMoreDataFromWeb();

            }
        });

        //listView的监听事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(SearchGoodsListActivity.this, GoodsDetailsActivity.class);
                intent.putExtra("goods_id", list.get(i-1).getGoods_id());
                startActivity(intent);
            }
        });


        //返回
        iv_back = (ImageView) findViewById(R.id.iv_back);
        //返回按钮监听事件
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    private void getMoreDataFromWeb() {
        tempList = new ArrayList<>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                final String keyword = et_search.getText().toString().trim();
                //定义路径
                String url = Constants.FLAGSHIP_STORE_URL +
                        "&key=" + key + "&order=" + order + "&curpage=" + currentPage + "&inkeyword=" + keyword;

                //使用OKHttp 获取解析数据
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();

                Call call = client.newCall(request);

                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(0);
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        tempList = SearchGoodsListJson.getSearchGoodsList(response.body().string());
                        if (tempList.size() > 0) {
                            handler.sendEmptyMessage(2);
                        }
                    }
                });

            }


        }).start();

    }

}